<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/11/21
 * Time: 10:49 AM
 */

namespace Biz\module\Decoupling\order;

use Biz\cache\UserBoughtGoods as UserBoughtGoodsCache;
use Biz\model\GoodsExtendInfo;
use Biz\model\GoodsSku;
use Biz\model\trade\Order as mOrder;
use Biz\model\trade\OrderGoods as mOrderGoods;
use Biz\model\trade\OrderOperateLog as mOrderOperateLog;
use Biz\model\trade\OrderPackage as mOrderPackage;
use Biz\model\trade\ShopCourier as mShopCourier;
use Biz\module\Classes\OrderGroupBuy as clsOrderGroupBuy;
use Biz\module\Classes\OrderSms as clsOrderSms;
use Biz\module\Classes\OrderWXNotice as clsOrderWXNotice;
use Biz\module\Decoupling\AbstractMain;
use Biz\pockets\constInterface\ActivityInfo;
use Biz\service\settlement\SettlementTransaction;
use Biz\service\trade\Order;
use Biz\service\trade\Pay;
use Biz\service\trade\ShopCourier as sShopCourier;
use Biz\service\TradeMsg;
use Doraemon\cache\Queue as cQueue;
use Doraemon\service\MemberRoleTag as sMemberRoleTag;
use Doraemon\service\Visitor;

class PayOrder extends AbstractMain
{
    const NAME = '支付成功事件回调';

    public function main($message, $data)
    {
        //解析 json 并赋值变量
        $appendData = [
            'orderShops' => [],
            'eventId' => $data['header']['event_id'],
            'uid' => $data['body']['uid'],
            'addTime' => $data['header']['addtime'],
            'orderNo' => $data['body']['order_no'],
            'isSys' => (int)$data['body']['is_sys'],
            'orderInfoList' => $data['body']['order_info_list'],
            'payWay' => $data['body']['pay_way'],
            'payNo' => $data['body']['pay_no'],
            'payTime' => $data['body']['pay_time'],
        ];


        //组装数据
        foreach ($appendData['orderInfoList'] as $orderInfo) {
            //shopId列表
            $appendData['orderShops'][] = ['shop_id' => $orderInfo['shop_id'], 'province' => $orderInfo['consignee_province'], 'order_no' => $orderInfo['order_no'],
                'uid' => $orderInfo['uid']];
        }


        $appendData['orderNos'] = array_column($appendData['orderInfoList'], 'order_no');

        $appendData['orderGoodsList'] = mOrderGoods::select(['title', 'sku_id', 'goods_id', 'order_no', 'promo_type', 'promo_id'], ['order_no' => $appendData['orderNos']]);


        $this->appendData($appendData);

    }

    protected function _exec_order_operate_log()
    {
        //日志和结算操作的处理
        foreach ($this->data['orderInfoList'] as $orderInfo) {

            //增加操作日志
            $result = mOrderOperateLog::createLog($orderInfo['shop_id'], $orderInfo['order_no'],
                mOrderOperateLog::TRADE_TYPE_ORDER, [
                    'operate_type' => mOrderOperateLog::OPERATE_TYPE_PAY_SUCCESS,
                    'operate_user_type' => mOrderOperateLog::OPERATE_USERTYPE_USER,
                    'operate_uid' => $orderInfo['uid'],
                ], '', sprintf("%s(%s)", $this->data['payWay'], $this->data['payNo']), '', [], $this->data['addTime']);

            $this->appendLog(sprintf('给订单%s增加操作日志', $orderInfo['order_no']), ['order_info' => $orderInfo]);

        }

    }

    protected function _exec_order_settlement_transaction()
    {
        //日志和结算操作的处理
        foreach ($this->data['orderInfoList'] as $orderInfo) {

            try {
                //结算流程
                SettlementTransaction::afterPaySuccess($orderInfo['shop_id'], $orderInfo['order_no'],
                    $orderInfo['pay_amount'], $this->data['payWay'], $orderInfo['shipping_amount']);

                $this->appendLog(sprintf('给订单%s发送结算信息', $orderInfo['order_no']), ['order_info' => $orderInfo]);

            } catch (\Exception $e) {
                $this->appendLog('支付成功发送结算信息 出现异常', [
                    "SettlementTransaction::afterPaySuccess" => [
                        $orderInfo['shop_id'],
                        $orderInfo['order_no'],
                        $orderInfo['pay_amount'],
                        $this->data['payWay'],
                        $orderInfo['shipping_amount']
                    ],
                    "e_msg" => $e->getMessage(),
                    "e_line" => $e->getLine(),
                    "e_file" => $e->getFile()
                ]);
                throw $e;
            }

        }
    }

    protected function _exec_send_sys_msg()
    {

        foreach ($this->data['orderInfoList'] as $orderInfo) {

            try {

                if (!empty($orderInfo) && !in_array($this->data['payWay'], [Pay::_PAY_WAYS_TUAN_MINIPROGRAM, Pay::_PAY_WAYS_THE_PARAGRAPH_MINIPROGRAM, Pay::_PAY_WAYS_ALIPAY_QRCODE])) {

                    //拼团的订单不发通知
                    if ($orderInfo['order_type'] == mOrder::ORDER_TYPE_PING_TUAN) {
                        return true;
                    }

                    $skuInfo = mOrderGoods::getFirstSkuInfo($orderInfo['order_no']);

                    TradeMsg::addMsg(TradeMsg::MSG_CODE_103, $orderInfo['uid'], $sysMsg = [
                        'order_no' => $orderInfo['order_no'],
                        'img' => isset($skuInfo['cover_img_thumb_url']) ? $skuInfo['cover_img_thumb_url'] : '',
                    ]);

                    $this->appendLog(sprintf('给订单%s发送试卖付款成功通知', $orderInfo['order_no']), ['order_info' => $orderInfo]);

                }
            } catch (\Exception $e) {
                $this->appendLog('支付成功发送系统通知 出现异常', [
                    "TradeMsg::addMsg" => [
                        TradeMsg::MSG_CODE_103,
                        $orderInfo['uid'],
                        [
                            'order_no' => $orderInfo['order_no'],
                            'img' => isset($skuInfo['cover_img_thumb_url']) ? $skuInfo['cover_img_thumb_url'] : '',
                        ]
                    ],
                    "e_msg" => $e->getMessage(),
                    "e_line" => $e->getLine(),
                    "e_file" => $e->getFile()
                ]);
                throw $e;
            }

        }
    }

    protected function _exec_add_bougth_goods()
    {
        //缓存所有子单下面的商品信息
        $cacheList = [];
        if (!empty($this->data['orderGoodsList'])) {
            foreach ($this->data['orderGoodsList'] as $info) {
                $cacheList[$info['goods_id']] = strtotime($this->data['payTime']);
            }
        }


        UserBoughtGoodsCache::addBoughtGoods($this->data['uid'], $cacheList);

        $this->appendLog('用户购买过的商品', array_merge($this->data, ['cache_list' => $cacheList]));
    }

    protected function _exec_ctrl_groupbuy_order()
    {
        //判断是否是团购单，进行支付后的团购单操作
        if (!empty($this->data['orderGoodsList'])) {
            foreach ($this->data['orderGoodsList'] as $orderGoods) {
                if ($orderGoods['promo_type'] == Order::ACTIVITY_TYPE_TUAN) {

                    $orderInfo = mOrder::getOrderInfo($orderGoods['order_no']);

                    if (!empty($orderInfo)) {
                        //如果是团购订单则反响回调团购人数
                        clsOrderGroupBuy::afterPaySuccessCallback($orderInfo['order_no'], $orderInfo['shop_id'], $orderGoods['title'], $orderInfo['pay_amount'], [$orderGoods['promo_id']], $orderInfo['buy_num']);

                        $this->appendLog('如果是团购订单则回调团购人数', array_merge($this->data, [
                            'callback_params' => [
                                'order_no' => $orderInfo['order_no'],
                                'shop_id' => $orderInfo['shop_id'],
                                'title' => $orderGoods['title'],
                                'pay_amount' => $orderInfo['pay_amount'],
                                'promo_ids' => [$orderGoods['promo_id']],
                                'buy_num' => $orderInfo['buy_num']
                            ]]));

                    }


                }
            }

        }
    }

    protected function _exec_double_eleven_pay_callback()
    {
        //双十一活动添加抽奖次数
        //sDoubleEleven::pay($uid);
    }

    protected function _exec_notice_seller_new_order()
    {

        $orderGoods = isset($this->data['orderGoodsList'][0]) ? $this->data['orderGoodsList'][0] : [];

        if ($orderGoods['promo_type'] == ActivityInfo::ACTIVITY_TYPE_PINTUAN) {
            return true;
        }


        //支付完成后提醒商家发货
        clsOrderSms::noticeSellerNewOrder($this->data['orderShops']);

        $this->appendLog('提醒商家发货', array_merge($this->data, ['order_shops' => $this->data['orderShops']]));


    }

    protected function _exec_notice_admin()
    {
        //支付完成后发送企业微信通知
        clsOrderWXNotice::noticeWechatNewOrder($this->data['orderShops'], $this->data['orderGoodsList']);

        $this->appendLog('通知管理员下单了', $this->data);

    }

    protected function _exec_save_role_tag()
    {
        //根据UID获取vid
        $vid = Visitor::getVidByUid($this->data['uid']);
        //付款
        cQueue::insertQueue('queue/UserRole/SaveRoleTag', $tagData = [
            'vid' => !empty($vid) ? $vid : 0,
            'tag_id' => sMemberRoleTag::ROLE_TAG_BUY,
            'value' => '2',
            'uid' => $this->data['uid'],
        ], cQueue::QUEUE_ROLE_TAG);

        $this->appendLog('给用户添加标签', array_merge($this->data, ['tag_data' => $tagData]));
    }

    protected function _exec_jiexuan_weixin_notice()
    {

        $orderPackageList = mOrderPackage::getExpressInfoList($this->data['orderNos']);

        foreach ($this->data['orderInfoList'] as $orderInfo) {

            if ($orderInfo['from_source'] != mOrder::FROM_SOURCE_PARAGRAPH_MINIPROGRAM) {
                return true;
            }

            //如果是门店自提，则不发通知
            $courierId = sShopCourier::getCourierIdByCourierName($orderPackageList[$orderInfo['order_no']][0]['express_company']);

            if ($courierId == mShopCourier::SELF_LIFTING_ID) {
                continue;
            }

            //获取该订单下面所有商品的信息
            $skuInfoList = mOrderGoods::getOrderGoodsList($orderInfo['order_no'], [], '', '*');

            $goodsTitles = array_column($skuInfoList, 'title', 'goods_id');
            $goodsIds = array_unique(array_column($skuInfoList, 'goods_id'));

            $goodsExtendInfos = GoodsExtendInfo::getExtendInfosByGoodsIds($goodsIds);

            $deliveryTime = [];
            $nowTime = time();
            foreach ($skuInfoList as $skuInfo) {
                $info = [];
                $info['title'] = $goodsTitles[$skuInfo['goods_id']];

                $goodsSku = GoodsSku::getInfo($skuInfo['sku_id']);


                $timeStamp = strtotime($goodsSku['forecast_ship_time']);

                if ($timeStamp > $nowTime) {
                    $info['time'] = date('m月d日', strtotime($goodsSku['forecast_ship_time'])) . ' 发货';
                } else {
                    $extendInfo = isset($goodsExtendInfos[$skuInfo['goods_id']]) ? $goodsExtendInfos[$skuInfo['goods_id']] : [];

                    $info['time'] = GoodsExtendInfo::getShippingTimeUnit($extendInfo['shipping_time_type'], $extendInfo['shipping_time']);
                }
                $deliveryTime[] = $info;
            }

            $goodsNum = count($skuInfoList);

            $deliveryTime = array_map(function ($v) use ($goodsNum) {
                if ($goodsNum > 1) {
                    return $v['title'] . $v['time'];
                } else {
                    return $v['time'];
                }
            }, $deliveryTime);

            $noticeData = [
                'keyword1' => count($skuInfoList) > 1 ? $skuInfoList[0]['title'] . " 等" : $skuInfoList[0]['title'],
                'keyword2' => $orderInfo['pay_amount'],
                'keyword3' => implode("\r\n", $deliveryTime),
                'keyword4' => $orderInfo['consignee_address'],
                'keyword5' => $orderInfo['message']

            ];


            TradeMsg::sendJieXuanProgramPayNotice($orderInfo['order_no'], $noticeData);
        }


    }

    protected function _exec_jiexuan_new_order_qywxchat()
    {
        $orderInfo = $this->data['orderInfoList'][0];

        if ($orderInfo['from_source'] == mOrder::FROM_SOURCE_PARAGRAPH_MINIPROGRAM || ($orderInfo['from_source'] == mOrder::FROM_SOURCE_APP && $orderInfo['shop_id'] == '4372030')) {
            try {
                clsOrderWXNotice::jiexuanNoticeWeChatNewOrder($this->data['orderInfoList'], $this->data['orderGoodsList']);
            } catch (\Exception $e) {
                $this->appendLog('支付成功后的节选新订单企业微信通知 出现异常', [
                    "clsOrderWXNotice::jiexuanNoticeWeChatNewOrder" => [
                        $this->data['orderInfoList'],
                        $this->data['orderGoodsList']
                    ],
                    "e_msg" => $e->getMessage(),
                    "e_line" => $e->getLine(),
                    "e_file" => $e->getFile()
                ]);
                throw $e;
            }
        }


    }

    protected function _exec_nippon()
    {
        \Biz\service\erp\Nippon::addOrder($this->data['orderInfoList'], $this->data['orderGoodsList']);
    }
}